package com.example.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.model.UserAddressDTO;

@Mapper
public interface ConUserAddressMapper {
        @Insert("insert into con_user_address(userId, addressId) values(#{userId}, #{addressId})")
        int addUserAddress(@Param("userId") Integer userId, @Param("addressId") Integer addressId);

        @Select("select a.id, a.address, cua.current from con_user_address cua join tb_address a on a.id = cua.addressId where cua.userId = #{userId}")
        String getAddressByUserId(@Param("userId") Integer userId);

        @Select("select a.id, a.address, cua.current from con_user_address cua join tb_address a on a.id = cua.addressId where cua.userId = #{userId}")
        List<UserAddressDTO> getAddressListByUserId(@Param("userId") Integer userId);

        @Update("UPDATE con_user_address cua " +
                        "JOIN tb_user u ON cua.userId = u.id " +
                        "SET cua.current = CASE " +
                        "    WHEN cua.addressId = #{oldAddressId} THEN false " +
                        "    WHEN cua.addressId = #{newAddressId} THEN true " +
                        "    ELSE cua.current " +
                        "END " +
                        "WHERE u.openId = #{openId} " +
                        "  AND (cua.addressId = #{oldAddressId} OR cua.addressId = #{newAddressId})")
        int updateAddress(@Param("openId") String openId, @Param("oldAddressId") Integer oldAddressId,
                        @Param("newAddressId") Integer newAddressId);

        @Update("update con_user_address cua join tb_user u on cua.userId = u.id set cua.current = true where u.openId = #{openId} and cua.addressId = #{newAddressId}")
        int initUserAddress(@Param("openId") String openId, @Param("newAddressId") Integer newAddressId);
}
